<?php
    $rootpath = '/home/content/58/7469158/html/';
    $isConnected = connectDatabase();
    
    $product = getProductToFetch();
    $asin = $product['asin'];
    
    $result = fetchProductByAsin($asin);
    
    if(empty($result)) { echo 'invalid ASIN: '.$asin; exit;}

    $data = array();
    
    $temp = (array)$result->Items->Item->ImageSets->ImageSet;
    $imageName = date('YmdHis').rand(100, 999).'.jpg';
    //echo '<pre>';var_dump((array)$temp['SwatchImage']);exit;
    
    $temp1 = (array)$temp['SwatchImage'];
    $isCopied = copy($temp1['URL'], $rootpath.'images/external/swatch/'.$imageName);
    
    $temp1 = (array)$temp['SmallImage'];
    $isCopied = copy($temp1['URL'], $rootpath.'images/external/small/'.$imageName);
    
    $temp1 = (array)$temp['ThumbnailImage'];
    $isCopied = copy($temp1['URL'], $rootpath.'images/external/thumbnail/'.$imageName);
    
    $temp1 = (array)$temp['TinyImage'];
    $isCopied = copy($temp1['URL'], $rootpath.'images/external/tiny/'.$imageName);
    
    $temp1 = (array)$temp['MediumImage'];
    $isCopied = copy($temp1['URL'], $rootpath.'images/external/medium/'.$imageName);
    
    $temp1 = (array)$temp['LargeImage'];
    $isCopied = copy($temp1['URL'], $rootpath.'images/external/large/'.$imageName);
    
    
    
    
    $temp = (array)$result->Items->Item->ItemAttributes;
    $data['brand']          = $temp['Brand'];
    $data['category_id']    = 1;
    $data['product_data_fetch_id'] = $product['id'];
    $data['image']          = NULL;
    $data['battery_type']   = $temp['BatteryType'];
    $data['binding']        = $temp['Binding'];
    $data['color']          = $temp['Color'];
    $data['features']       = implode('|', $temp['Feature']);
    $data['form_facter']    = $temp['FormFactor'];
    $data['included_softwares']    = $temp['IncludedSoftware'];
    $data['image']          = $imageName;
    $data['label']          = $temp['Label'];
    $data['model']          = $temp['Model'];
    $data['operating_system']= $temp['OperatingSystem'];
    $data['release_date']   = $temp['ReleaseDate'];
    $data['title']          = $temp['Title'];
    $data['upc']            = $temp['UPC'];

    $temp = (array)$result->Items->Item->ItemAttributes->ListPrice;
    $data['list_price']     = $temp['Amount'];
    
    $temp = (array)$result->Items->Item->ItemAttributes->ItemDimensions;
    $data['dimensions']     = implode('|', $temp); 
     
    //$temp = (array)$result->Items->Item->EditorialReviews->EditorialReview;
    $temp = (array)$result->Items->Item->EditorialReviews;
    $temp = (array)$temp['EditorialReview'][1];
    
    $data['description']    = $temp['Content'];
    
   
    $isEntered = enterInDatabase($data);
    
    if($isEntered) {
        $isUpdated = updateFetchTableStatus($product['id']);
        
        if(!empty($isUpdated)) {
            echo 'Record processed successfully!';
        }
    }
    
    //var_dump($result->Items->Item->EditorialReviews);
    
    /*
    echo "Sales Rank : {$result->Items->Item->SalesRank}<br>";
    echo "ASIN : {$result->Items->Item->ASIN}<br>";
    echo "<br><img src=\"" . $result->Items->Item->MediumImage->URL . "\" /><br>";
    */

//-----------------------------------------------------------------------------------------------//

function enterInDatabase($data) {
    $keys  = array();
    $values = array();
    
    foreach($data as $key => $value) {
            $keys[] = $key;
            $values[] = "'".mysql_real_escape_string($value)."'";
    }
    
    $keyString = implode(',', $keys);
    $valueString = implode(',', $values);
    
    $query = "INSERT INTO products (".$keyString.") VALUES (".$valueString.")";
    
    $resultSet = mysql_query($query);
    
    if(!$resultSet) { echo mysql_error(); exit; }
    return $resultSet;
}


function getProductToFetch() {
    $query = "SELECT *
                FROM product_data_fetch
                WHERE fetch_status = 0
                    LIMIT 1";
    $resultSet = mysql_query($query);
    
    if(!$resultSet) { echo mysql_error(); exit; }
    
    $row = mysql_fetch_assoc($resultSet);
    
    return $row;
}

function connectDatabase() {
    $host = 'impdamazon.db.7469158.hostedresource.com';
    $username = 'impdamazon';
    $password = 'Password@1';
    $dbname = 'impdamazon';
    
    $isConnected = mysql_connect($host, $username, $password);
    $isSelected = mysql_select_db($dbname);
    
    return $isSelected ? true : false;
}

function updateFetchTableStatus($id) {
    if(empty($id)) { echo 'Invalid fetch id'; exit; }
    
    $query = "UPDATE product_data_fetch
                SET fetch_status = 1
                WHERE id = ".$id;
    
    $resultSet = mysql_query($query);
    
    if(!$resultSet) { echo mysql_error(); exit; }
    
    return $resultSet;
}

function fetchProductByAsin($asin) {
    /* Example usage of the Amazon Product Advertising API */
    include("amazon_api_class.php");
    
    
    $obj = new AmazonProductAPI();
    
    try
    {
        /*
        $result = $obj->searchProducts("X-Men Origins",
                                       AmazonProductAPI::DVD,
                                       "TITLE");
        */
        $result = $obj->getItemByAsin($asin);
    }
    catch(Exception $e)
    {
        echo $e->getMessage();
    }
    
    return $result;
}
?>